package cn.tedu.travelsystem.order.controller;

import cn.tedu.travelsystem.base.response.JsonResult;
import cn.tedu.travelsystem.order.pojo.dto.OrderaddParam;
import cn.tedu.travelsystem.order.pojo.entity.Order;

import cn.tedu.travelsystem.order.service.OrderService;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

import static cn.tedu.travelsystem.base.response.JsonResult.*;

@Validated
@Slf4j
@Api(tags = "09.订单模块")
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @PostMapping("insertOrder")
    @ApiOperation("增加订单功能")
    @ApiOperationSupport(order = 10)
    public JsonResult insertOrder(@Validated @RequestBody OrderaddParam orderaddParam) {
        log.debug("OrderaddParam = " + orderaddParam);
        Order order = new Order();
        BeanUtils.copyProperties(orderaddParam, order);
        order.setCreateTime(new Date());
        order.setOrderStatus(String.valueOf(Order.OrderStatus.UNPAID)); // 新增订单默认未支付
        orderService.createOrder(order);
        return ok();
    }

    @ApiOperation("支付订单")
    @ApiOperationSupport(order = 20)
    @PutMapping("/pay/{orderId}")
    public JsonResult payOrder(@PathVariable int orderId) {
        boolean result = orderService.payOrder(orderId);
        if (result) {
            return ok("支付成功");
        } else {
            return error("支付失败，订单状态不正确或不存在");
        }
    }

    @ApiOperation("取消订单")
    @ApiOperationSupport(order = 40)
    @PutMapping("/cancel/{orderId}")
    public JsonResult cancelOrder(@PathVariable int orderId) {
        boolean result = orderService.cancelOrder(orderId);
        if (result) {
            return ok("取消成功");
        } else {
            return error("取消失败，订单状态不正确或不存在");
        }
    }

    @ApiOperation("查询订单详情")
    @ApiOperationSupport(order = 30)
    @GetMapping("/get/{orderId}")
    public JsonResult getOrder(@PathVariable int orderId) {
        Order order = orderService.getOrderById(orderId);
        if (order != null) {
            return ok(order);
        } else {
            return ok("订单不存在");
        }
    }
}
